# -*- coding:utf8 -*-
import json
import typing
import ddddocr
import traceback
from scrapy import Request
from squirrel_core.frame.spider_makaka import MakakaSpider


class chengdufeiyi_regist(MakakaSpider):
    name = "chengdufeiyi_regist"
    start_url = "https://api-changzheng.chinaath.com/changzheng-website-center-api/api/official/website/domain/name/selectByDomainName?domainName=chengdu.shuzixindong.com"
    img_url = "https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getUniqueIdByBusinessType?imageVerifyBusinessType=2"
    yzm_url = "https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getVerifyCode?uniqueId={}"
    register_url = "https://api-changzheng.chinaath.com/changzheng-website-center-api/api/official/website/getUserRegistrationBaseInfo"
    header = {
        "Host": "api-changzheng.chinaath.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0",
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Content-Type": "application/json",
        "Origin": "https://chengdu.shuzixindong.com",
        "Referer": "https://chengdu.shuzixindong.com/"
    }

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            card_num = data.get("card_num", "")
            yield Request(url=self.start_url, callback=self.parse, dont_filter=True,
                          cb_kwargs={"card_num": card_num}, errback=self.err_parse)

    def parse(self, response, **kwargs):
        try:
            self.logger.info("开始获取raceid")
            data = json.loads(response.text).get("data", "")
            race_id = data.get("raceId", "")
            domain_name = data.get("domainName", "")
            kwargs.update({"race_id": race_id, "domain_name": domain_name})
            yield Request(url=self.img_url, callback=self.img_id_parse, dont_filter=True,
                          cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"请求raceid时出错：{traceback.format_exc()}")

    def img_id_parse(self, response, **kwargs):
        try:
            self.logger.info("开始获取imageUniqueId")
            data = json.loads(response.text).get("data", "")
            kwargs.update({"imageUniqueId": data})
            url = self.yzm_url.format(data)
            yield Request(url=url, callback=self.yzm_parse, dont_filter=True, cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"请求imageUniqueId时出错：{traceback.format_exc()}")

    def yzm_parse(self, response, **kwargs):
        try:
            self.logger.info("开始打码")
            race_id = kwargs.get("race_id", "")
            domain_name = kwargs.get("domain_name", "")
            image_id = kwargs.get("imageUniqueId", "")
            card_num = kwargs.get("card_num", "")
            ocr = ddddocr.DdddOcr(show_ad=False, beta=True)
            yzm = ocr.classification(response.body)
            regist_data = {"cardNumber": card_num, "domainName": domain_name,
                           "imageUniqueId": image_id, "imageVerifyCode": yzm,
                           "raceId": int(race_id)}
            yield Request(url=self.register_url, callback=self.register_parse, method="POST", headers=self.header,
                          body=json.dumps(regist_data), dont_filter=True, cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"打码时出错：{traceback.format_exc()}")

    def register_parse(self, response, **kwargs):
        try:
            msg = json.loads(response.text).get("msg", "")
            if msg == "验证码错误":
                self.logger.info(f"查询报名信息时验证码错误，重新打码")
                yield Request(url=self.start_urls[0], callback=self.parse, dont_filter=True,
                              cb_kwargs=kwargs, errback=self.err_parse)
            else:
                self.logger.info("开始查询报名信息")
                register_info = {}
                content = json.loads(response.text)
                data_list = content.get("data", {}).get("registrationFromInfo", [])
                for data in data_list:
                    key = data.get("componentName", "")
                    value = data.get("componentValue", "")
                    register_info[key] = value
                register_info = register_info
                result = self.result_item_assembler(response)
                result['result_data'] = {'register_info': register_info}
                yield result
        except Exception:
            self.logger.error(f"请求报名信息时出错：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")
